package net.keebook.webapp.bean;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.dao.ShareRequestDao;
import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.ShareRequest;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;


@ManagedBean
@RequestScoped
public class JoinBean {
	private ShareRequest shareRequest;
	private String keeBookName;
	
	@Inject
	private KeeBookDao keeBookDao;
	
	@Inject
	private ShareRequestDao shareRequestDao;
	
	@Inject
	private UserDao userDao;
	
	private SessionModel sessionModel;
	
	@PostConstruct
	public void init() throws IOException {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
		
		String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
		if (id == null) {
			FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
			return;
		}
		ShareRequest sr = getShareRequestDao().get(id);
		if (sr == null) {
			FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
			return;
		}
		setShareRequest(sr);
	}
	
	public void join() throws IOException {
		User user = getUserDao().get(getSessionModel().getUserId());
		
		ShareRequest sr = getShareRequest();
		getKeeBookDao().setAccessRight(user, sr.getKeeBook(), sr.getAccessRight());
		getShareRequestDao().delete(sr);
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	}
	
	public void dismiss() throws IOException {
		ShareRequest sr = getShareRequest();
		getShareRequestDao().delete(sr);
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	}

	public String getKeeBookName() {
		return keeBookName;
	}

	public void setKeeBookName(String keeBookName) {
		this.keeBookName = keeBookName;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}

	public ShareRequestDao getShareRequestDao() {
		return shareRequestDao;
	}

	public void setShareRequestDao(ShareRequestDao shareRequestDao) {
		this.shareRequestDao = shareRequestDao;
	}

	public ShareRequest getShareRequest() {
		return shareRequest;
	}

	public void setShareRequest(ShareRequest shareRequest) {
		this.shareRequest = shareRequest;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
